package com.spzx.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.cart.api.RemoteCartService;
import com.spzx.cart.api.domain.CartInfo;
import com.spzx.common.core.constant.SecurityConstants;
import com.spzx.common.core.context.SecurityContextHolder;
import com.spzx.common.core.domain.R;
import com.spzx.common.core.exception.ServiceException;
import com.spzx.common.core.utils.StringUtils;
import com.spzx.common.core.utils.bean.BeanUtils;
import com.spzx.common.core.utils.uuid.UUID;
import com.spzx.common.rabbit.constant.MqConst;
import com.spzx.common.rabbit.service.RabbitService;
import com.spzx.order.api.domain.OrderInfo;
import com.spzx.order.api.domain.OrderItem;
import com.spzx.order.domain.OrderLog;
import com.spzx.order.domain.vo.OrderForm;
import com.spzx.order.domain.vo.TradeVo;
import com.spzx.order.mapper.OrderInfoMapper;
import com.spzx.order.mapper.OrderItemMapper;
import com.spzx.order.mapper.OrderLogMapper;
import com.spzx.order.service.IOrderInfoService;
import com.spzx.product.api.RemoteProductService;
import com.spzx.product.api.domain.vo.SkuLockVo;
import com.spzx.product.api.domain.vo.SkuPrice;
import com.spzx.user.api.RemoteUserAddressService;
import com.spzx.user.domain.UserAddress;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements IOrderInfoService {
    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private RemoteCartService remoteCartService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private RemoteProductService remoteProductService;

    @Autowired
    private RemoteUserAddressService remoteUserAddressService;

    @Autowired
    RabbitService rabbitService; //来自于公共模块：spzx-common-rabbit

    /**
     * 查询订单列表
     *
     * @param orderInfo 订单
     * @return 订单
     */
    @Override
    public List<OrderInfo> selectOrderInfoList(OrderInfo orderInfo) {
        return orderInfoMapper.selectOrderInfoList(orderInfo);
    }

    /**
     * 查询订单
     *
     * @param id 订单主键
     * @return 订单
     */
    @Override
    public OrderInfo selectOrderInfoById(Long id) {
        OrderInfo orderInfo = orderInfoMapper.selectById(id);
        List<OrderItem> orderItemList = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, id));
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }


    //============以下接口  给前台会员系统使用的接口===================================================


    @Override
    public TradeVo orderTradeData() {

        //1.获取List<OrderItem>
        //1.1 远程调用购物车服务，获取勾选购买商品列表List<CartInfo>
        Long userId = SecurityContextHolder.getUserId(); //通过ThreadLocal从线程上获取共享数据
        R<List<CartInfo>> cartCheckedListResult = remoteCartService.getCartCheckedList(userId, SecurityConstants.INNER);
        if(cartCheckedListResult.getCode() == R.FAIL){
            throw new ServiceException(cartCheckedListResult.getMsg());
        }


        //1.2 将List<CartInfo>转换为List<OrderItem>
        List<CartInfo> cartInfoList = cartCheckedListResult.getData();
        if(CollectionUtils.isEmpty(cartInfoList)){
            throw new ServiceException("数据不存在");
        }
        List<OrderItem> orderItemList = cartInfoList.stream().map((cartInfo) -> {
            OrderItem orderItem = new OrderItem();
            BeanUtils.copyProperties(cartInfo, orderItem);
            return orderItem;
        }).toList();


        //2.获取总价格
        BigDecimal totalAmount =  new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            BigDecimal multiply = orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())); //单价 * 数量
            totalAmount = totalAmount.add(multiply);
        }

        //3.生成交易流水号
        String tradeNo = generateTradeNo(userId);

        //4.封装数据
        TradeVo tradeVo = new TradeVo();
        tradeVo.setOrderItemList(orderItemList);
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setTradeNo(tradeNo); //交易流水号，也是保存订单的订单号。用于下单去重。

        //5.返回结果
        return tradeVo;
    }

    @NotNull
    private String generateTradeNo(Long userId) {
        String tradeNo = UUID.randomUUID().toString().replaceAll("-","");
        String userTradeKey = "user:tradeNo:" + userId;
        redisTemplate.opsForValue().set(userTradeKey,tradeNo,5, TimeUnit.MINUTES);
        return tradeNo;
    }


    @Override
    public Long submitOrder(OrderForm orderForm) {

        Long userId = SecurityContextHolder.getUserId();

        // 下订单业务逻辑：
        // 1.验证用户重复提交表单
        //解决去重问题，代码不具备原子性，可能出现并发问题。如何解决：Lua
        String userTradeKey = "user:tradeNo:" + userId;
        String tradeNoFromForm = orderForm.getTradeNo();
        /*
        String tradeNoRedis = (String)redisTemplate.opsForValue().get(userTradeKey); //5分钟有效
        if(tradeNoFromForm!=null && !tradeNoFromForm.equals(tradeNoRedis)){
            throw new ServiceException("重复提交");
        }
        redisTemplate.delete(userTradeKey);*/

        String script = "if redis.call('get',KEYS[1]) == ARGV[1]\n" +
                "then\n" +
                "return redis.call('del',KEYS[1])\n" +
                "else\n" +
                "return 0\n" +
                "end;";
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script,Long.class);
        Long result = (Long)redisTemplate.execute(redisScript, Arrays.asList(userTradeKey), tradeNoFromForm);
        if(result == 0){
            throw new ServiceException("重复提交");
        }

        // 2.验证表单参数是否空
        List<OrderItem> orderItemList = orderForm.getOrderItemList(); //交易页面商品价格其实就是购物车添加商品当时价格
        if(CollectionUtils.isEmpty(orderItemList)){
            throw new ServiceException("数据为空");
        }

        // 3.校验价格变化
        List<Long> skuIdList = orderItemList.stream().map(OrderItem::getSkuId).toList();
        R<List<SkuPrice>> skuPriceListResult = remoteProductService.getSkuPriceList(skuIdList, SecurityConstants.INNER);
        if(skuPriceListResult.getCode() == R.FAIL){
            throw new ServiceException(skuPriceListResult.getMsg());
        }
        List<SkuPrice> skuPriceList = skuPriceListResult.getData(); //数据库最新商品价格
        // List<SkuPrice>  转   Map<Integer,BigDecimal>
        Map<Long, BigDecimal> skuIdToSkuPriceMap = skuPriceList.stream()
                .collect(Collectors.toMap(SkuPrice::getSkuId, SkuPrice::getSalePrice));

        StringBuilder resultStr = new StringBuilder("");
        for (OrderItem orderItem : orderItemList) {
            BigDecimal skuPriceFromDB = skuIdToSkuPriceMap.get(orderItem.getSkuId());
            if(orderItem.getSkuPrice().compareTo(skuPriceFromDB) != 0){
                resultStr.append("商品["+orderItem.getSkuName()+"]价格有变动;");
            }
        }

        if(resultStr.toString().length()>0){
            //更新购物车价格
            remoteCartService.updateCartPrice(userId,SecurityConstants.INNER);
            throw new ServiceException(resultStr.toString());
        }

        // 4.校验库存、锁定库存
        List<SkuLockVo> skuLockVoList = orderItemList.stream().map((orderItem) -> {
            SkuLockVo skuLockVo = new SkuLockVo();
            skuLockVo.setSkuId(orderItem.getSkuId());
            skuLockVo.setSkuNum(orderItem.getSkuNum());
            //skuLockVo.setIsHaveStock(false); //调用检查与锁定库存前，不知道库存够不够的。默认都是false
            return skuLockVo;
        }).toList();
        R<String> checkAndLockResult = remoteProductService.checkAndLock(orderForm.getTradeNo(), skuLockVoList, SecurityConstants.INNER);
        if(checkAndLockResult.getCode() == R.FAIL){
            throw new ServiceException(checkAndLockResult.getMsg());
        }
        String checkAndLockResultStr = checkAndLockResult.getData();
        if(StringUtils.isNotEmpty(checkAndLockResultStr)){
            throw new ServiceException(checkAndLockResultStr);
        }

        // 5.保存订单（订单表、订单项表、订单日志表）
        Long orderId = null;
        try {
            orderId = this.saveOrder(orderForm);
        } catch (Exception e) {
            e.printStackTrace();
            //发普通消息，解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT,MqConst.ROUTING_UNLOCK,orderForm.getTradeNo());
            throw new ServiceException("下单失败");
        }

        // 6.删除购物车选中商品
        remoteCartService.deleteCartCheckedList(userId,SecurityConstants.INNER);

        // 7.发送延迟消息，15分钟内等待支付；15后如果没有支付需要解锁库存。
        rabbitService.sendDealyMessage(MqConst.EXCHANGE_CANCEL_ORDER,
                MqConst.ROUTING_CANCEL_ORDER,
                orderId.toString(),
                MqConst.CANCEL_ORDER_DELAY_TIME);

        return orderId;
    }

    @Transactional
    public Long saveOrder(OrderForm orderForm) {
        Long userId = SecurityContextHolder.getUserId();
        String userName = SecurityContextHolder.getUserName();
        //1.保存订单
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setOrderNo(orderForm.getTradeNo());
        orderInfo.setUserId(userId);
        orderInfo.setNickName(userName);
        orderInfo.setRemark(orderForm.getRemark());
        UserAddress userAddress = remoteUserAddressService.getUserAddress(orderForm.getUserAddressId(), SecurityConstants.INNER).getData();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());

        List<OrderItem> orderItemList = orderForm.getOrderItemList();
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount); //实付总价格(含优惠价和运费)
        orderInfo.setCouponAmount(new BigDecimal(0));
        orderInfo.setOriginalTotalAmount(totalAmount); //商品总价格(只包含商品价格)
        orderInfo.setFeightFee(orderForm.getFeightFee());
        //OrderInfo类的orderStatus属性的类型改为Integer
        orderInfo.setOrderStatus(0);
        orderInfoMapper.insert(orderInfo); //主键回填

        //2.保存订单项
        //orderItemList = orderForm.getOrderItemList();
        for (OrderItem orderItem : orderItemList) {
            orderItem.setOrderId(orderInfo.getId());
            orderItem.setCreateTime(new Date());
            orderItem.setUpdateTime(new Date());
            orderItemMapper.insert(orderItem);
        }

        //3.保存订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLog.setOperateUser("用户");
        orderLogMapper.insert(orderLog);

        return orderInfo.getId();
    }



    /**
     * 关单：
     *      未支付订单状态  ->  订单取消状态
     * @param orderId 订单id
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void processCloseOrder(Long orderId) {
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        if(null != orderInfo && orderInfo.getOrderStatus().intValue() == 0) { //  订单状态orderStatus=0 说明15分钟未支付。
            orderInfo.setOrderStatus(-1); //  -1 取消订单
            orderInfo.setCancelTime(new Date());
            orderInfo.setCancelReason("未支付自动取消");
            orderInfoMapper.updateById(orderInfo);

            //记录日志
            OrderLog orderLog = new OrderLog();
            orderLog.setOrderId(orderInfo.getId());
            orderLog.setProcessStatus(-1);
            orderLog.setNote("系统取消订单");
            orderLogMapper.insert(orderLog);

            //发送MQ消息通知商品系统解锁库存
            rabbitService.sendMessage(MqConst.EXCHANGE_PRODUCT, MqConst.ROUTING_UNLOCK, orderInfo.getOrderNo());
        }
    }


    @Override
    public OrderInfo getByOrderNo(String orderNo) {
        OrderInfo orderInfo = orderInfoMapper.selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo));

        List<OrderItem> orderItemList = orderItemMapper
                .selectList(new LambdaQueryWrapper<OrderItem>().eq(OrderItem::getOrderId, orderInfo.getId()));

        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }


    @Override
    public void processPaySucess(String orderNo) {
        //获取订单信息
        OrderInfo orderInfo = orderInfoMapper
                .selectOne(new LambdaQueryWrapper<OrderInfo>().eq(OrderInfo::getOrderNo, orderNo)
                        .select(OrderInfo::getId, OrderInfo::getOrderStatus));
        //未支付
        if(orderInfo.getOrderStatus().intValue() == 0) { //订单状态是未支付0，修改为1已支付
            orderInfo.setOrderStatus(1);
            orderInfo.setPaymentTime(new Date());
            orderInfoMapper.updateById(orderInfo);
        }
    }
}